<template>
  <yy-paging
    v-model="dataList"
    @query="queryList"
    ref="paging"
    :auto="true"
    @scroll="scroll"
    :refresher-enabled="false"
  >
    <template #top>
      <u-navbar
        back-text=""
        :is-back="false"
        title=""
        :background="{ backgroundColor: isScroll ? '#F2F5F7' : 'transparent' }"
        :border-bottom="false"
        :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
      >
        <view class="grid grid-cols-3 items-center px-3 w-full">
          <view class="flex col-span-1 items-center" @click="complete">
            <image src="/static/dddr128.png" mode="aspectFill" class="size-6" />
          </view>
          <view class="flex col-span-1 justify-center">
            <view class="text-[1rem] text-[#000] font-bold"> 选择鱼种 </view>
          </view>
          <view class="flex col-span-1 justify-end" @click="complete">
            <view class="text-[.875rem]" :class="selectedFish.length > 0 ? 'text-[#00BFBF]' : 'text-[#5C6068]'">
              完成
            </view>
          </view>
        </view>
      </u-navbar>
      <!-- 搜索 -->
      <view class="flex flex-col gap-3 px-4 py-3">
        <view class="w-full h-[2.25rem] bg-[#FFFFFF] rounded-[.5rem] flex items-center gap-3 px-4" @click="goToSearch">
          <image src="/static/dddr59.png" class="!size-4" mode="aspectFill" />
          <view class="h-[.625rem] border-l border-solid border-[#C0C4CC]"> </view>
          <view class="text-[.8125rem] text-[#8E9299]"> 搜索想找的鱼种、钓点名称 </view>
        </view>
        <view class="flex gap-1 items-center" v-if="selectedFish.length">
          <view class="text-[.875rem] text-[#161A24]"> 已选鱼种</view>
          <view class="text-[.75rem] text-[#8E9299]">({{ selectedFish.length }}/{{ maxSelectCount }})</view>
        </view>
        <view class="flex flex-wrap gap-2" v-if="selectedFish.length">
          <view v-for="(i, k) in selectedFish" class="flex gap-1 items-center px-4 py-2 bg-white rounded-full" :key="k">
            <view class="text-[.75rem] text-[#161A24]">
              {{ i.name }}
              <text v-if="i.alias"> ({{ i.alias }}) </text>
            </view>
            <image src="/static/dddr24.png" @click="deleteSelected(i)" mode="aspectFill" class="size-4" />
          </view>
        </view>
        <view class="text-[.875rem] text-[#161A24]"> 全部鱼种</view>
      </view>
    </template>

    <!-- 使用内置列表渲染，无需手动循环 -->
    <!-- <template #cell="{ item }">
      <view class="px-4">
        <view class="bg-[#FFFFFF] rounded-[.75rem] flex justify-between items-center p-4 mb-3" @click="toggleSelect(item)">
          <view class="flex gap-4 items-center">
            <view class="w-[4.25rem] h-[2.5rem] rounded-[.25rem] overflow-hidden" @click.stop="previewImage(item.thumb)">
              <u-image :src="vk.myfn.handleImageUrl(item.thumb)" class="!size-full" mode="aspectFill" :lazy-load="true" />
            </view>
            <view class="text-[.875rem] text-[#161A24]">{{ item.name }}</view>
          </view>
          <view
            class="size-5 flex justify-center items-center place-content-center rounded-full transition-all duration-300"
            :class="selectedFishMap[item.id] ? 'bg-[#00BFBF] border-[#00BFBF]' : 'bg-[#FFFFFF] border'"
          >
            <u-icon name="checkmark" color="#FFFFFF" size="20" v-if="selectedFishMap[item.id]"></u-icon>
          </view>
        </view>
      </view>
    </template> -->
    <view class="px-4" v-for="(item, k) in dataList" :key="k">
      <view
        class="bg-[#FFFFFF] rounded-[.75rem] flex justify-between items-center p-4 mb-3"
        @click="toggleSelect(item)"
      >
        <view class="flex gap-4 items-center">
          <view class="w-[4.25rem] h-[2.5rem] rounded-[.25rem] overflow-hidden" @click.stop="previewImage(item.thumb)">
            <u-image :src="vk.myfn.handleImageUrl(item.thumb)" class="!size-full" mode="aspectFill" :lazy-load="true" />
          </view>
          <!-- {{ vk.myfn.handleImageUrl(item.thumb) }} -->
          <view class="text-[.875rem] text-[#161A24]">
            {{ item.name }}

            <text v-if="item.alias"> ({{ item.alias }}) </text>
          </view>
        </view>
        <view
          class="size-5 flex justify-center items-center place-content-center rounded-full transition-all duration-300"
          :class="selectedFishMap[item.id] ? 'bg-[#00BFBF] border-[#00BFBF]' : 'bg-[#FFFFFF] border'"
        >
          <u-icon name="checkmark" color="#FFFFFF" size="20" v-if="selectedFishMap[item.id]"></u-icon>
        </view>
      </view>
    </view>

    <template #empty>
      <yy-empty></yy-empty>
    </template>
    <template #loadingMoreNoMore>
      <yy-nomore></yy-nomore>
    </template>
  </yy-paging>
</template>

<script>
  export default {
    data() {
      return {
        isScroll: false, // 是否滚动
        dataList: [], // 数据列表
        selectedFish: [], // 已选中的鱼种
        selectedFishMap: {}, // 已选中鱼种的映射表，用于快速查找
        maxSelectCount: 5, // 最大可选数量
        basan_type: '' // 鱼种类型
      }
    },

    onLoad(options) {
      this.basan_type = options.basan_type
      const eventChannel = this.getOpenerEventChannel()
      // 监听data事件，获取上一页面通过eventChannel.emit传送到当前页面的数据
      if (eventChannel.on) {
        eventChannel.on('datass', data => {
          console.log('data==> ', data)
          this.selectedFish = data
        })
      }
    },
    watch: {
      // 监听selectedFish变化，更新映射表
      selectedFish: {
        handler(newVal) {
          this.selectedFishMap = {}
          newVal.forEach(fish => {
            this.selectedFishMap[fish.id] = true
          })
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      deleteSelected(i) {
        // 从已选中的鱼种列表中删除指定索引的鱼种
        const index = this.selectedFish.findIndex(fish => fish.id === i.id)
        if (index > -1) {
          this.selectedFish.splice(index, 1)
        }
      },
      complete() {
        vk.$emit('update', this.selectedFish)
        vk.navigateBack()
      },
      previewImage(thumb) {
        vk.myfn.previewImage({
          urls: [thumb],
          current: 1 // 显示第二张图片
        })
      },

      // 监听滚动
      scroll(e) {
        this.isScroll = e.detail.scrollTop > 0
      },

      // 加载数据
      async queryList(page, limit) {
        let obj = {
          page,
          limit,
          basan_type: this.basan_type
        }
        let res = await api.getFishOptions(obj)
        this.$refs.paging.setLocalPaging(res.data.fish_species)
      },

      // 切换选中状态
      toggleSelect(item) {
        if (this.selectedFishMap[item.id]) {
          // 已选中，取消选择
          const index = this.selectedFish.findIndex(fish => fish.id === item.id)
          if (index > -1) {
            this.selectedFish.splice(index, 1)
            delete this.selectedFishMap[item.id] // 使用JavaScript的delete操作符
          }
        } else {
          // 未选中，添加到选中列表
          if (this.selectedFish.length >= this.maxSelectCount) {
            uni.showToast({
              title: `最多只能选择${this.maxSelectCount}种鱼`,
              icon: 'none'
            })
            return
          }
          this.selectedFish.push(item)
          this.$set(this.selectedFishMap, item.id, true) // 直接添加到映射表
        }
      },

      // 判断是否已选中
      isSelected(item) {
        return !!this.selectedFishMap[item.id]
      },

      // 跳转到搜索页面
      goToSearch() {
        vk.navigateTo({
          url: `/pages/index/searchForFish?basan_type=${this.basan_type}`,
          events: {
            update: data => {
              this.selectedFish = data
            }
          },
          success: res => {
            res.eventChannel.emit('data', this.selectedFish)
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .size-full {
    width: 100%;
    height: 100%;
  }

  .size-4 {
    width: 16px;
    height: 16px;
  }

  .size-5 {
    width: 20px;
    height: 20px;
  }
</style>
